{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\62744\\Anaconda2\\lib\\site-packages\\pandas\\_libs\\__init__.py:3: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected zd, got zd\n",
      "  from .tslib import iNaT, NaT, Timestamp, Timedelta, OutOfBoundsDatetime\n",
      "C:\\Users\\62744\\Anaconda2\\lib\\site-packages\\pandas\\__init__.py:26: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected zd, got zd\n",
      "  from pandas._libs import (hashtable as _hashtable,\n",
      "C:\\Users\\62744\\Anaconda2\\lib\\site-packages\\pandas\\core\\dtypes\\common.py:6: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected zd, got zd\n",
      "  from pandas._libs import algos, lib\n",
      "C:\\Users\\62744\\Anaconda2\\lib\\site-packages\\pandas\\core\\util\\hashing.py:7: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected zd, got zd\n",
      "  from pandas._libs import hashing, tslib\n",
      "C:\\Users\\62744\\Anaconda2\\lib\\site-packages\\pandas\\core\\indexes\\base.py:6: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected zd, got zd\n",
      "  from pandas._libs import (lib, index as libindex, tslib as libts,\n",
      "C:\\Users\\62744\\Anaconda2\\lib\\site-packages\\pandas\\core\\indexes\\datetimelike.py:28: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected zd, got zd\n",
      "  from pandas._libs.period import Period\n",
      "C:\\Users\\62744\\Anaconda2\\lib\\site-packages\\pandas\\core\\sparse\\array.py:32: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected zd, got zd\n",
      "  import pandas._libs.sparse as splib\n",
      "C:\\Users\\62744\\Anaconda2\\lib\\site-packages\\pandas\\core\\window.py:36: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected zd, got zd\n",
      "  import pandas._libs.window as _window\n",
      "C:\\Users\\62744\\Anaconda2\\lib\\site-packages\\pandas\\core\\groupby.py:66: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected zd, got zd\n",
      "  from pandas._libs import lib, groupby as libgroupby, Timestamp, NaT, iNaT\n",
      "C:\\Users\\62744\\Anaconda2\\lib\\site-packages\\pandas\\core\\reshape\\reshape.py:30: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected zd, got zd\n",
      "  from pandas._libs import algos as _algos, reshape as _reshape\n",
      "C:\\Users\\62744\\Anaconda2\\lib\\site-packages\\pandas\\io\\parsers.py:43: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected zd, got zd\n",
      "  import pandas._libs.parsers as parsers\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "\n",
    "import numpy as np\n",
    "import scipy.sparse as ss\n",
    "import scipy.io as sio\n",
    "\n",
    "#保存数据\n",
    "import cPickle\n",
    "\n",
    "from sklearn.preprocessing import normalize"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3391\n"
     ]
    }
   ],
   "source": [
    "ulist = cPickle.load(open(\"PE_userIndex.pkl\", 'rb'))\n",
    "numberuser = len(ulist)\n",
    "print(numberuser)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "#用户-事件关系矩阵\n",
    "userEventScores = sio.mmread(\"PE_userEventScores\")\n",
    "\n",
    "#后续用于将用户朋友参加的活动影响到用户\n",
    "eventsForUser = cPickle.load(open(\"PE_eventsForUser.pkl\", 'rb'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "#用户有多少个朋友\n",
    "numFriends = np.zeros((numberuser))\n",
    "userFriends = ss.dok_matrix((numberuser, numberuser))\n",
    "    \n",
    "fin = open(\"user_friends.csv\", 'rb')\n",
    "#字段：user，friends\n",
    "fin.readline()                # skip header\n",
    "\n",
    "#ln = 0\n",
    "for line in fin:  #对每个用户        \n",
    "    cols = line.strip().split(\",\")\n",
    "    user = str(cols[0])    #user\n",
    "    \n",
    "    if ulist.has_key(user):   #该用户在训练集和测试集的用户列表中\n",
    "        friends = cols[1].split(\" \")  #friends\n",
    "        i = ulist[user]       #该用户的索引\n",
    "        numFriends[i] = len(friends)\n",
    "        for friend in friends:  #该用户的每个朋友\n",
    "            str_friend = str(friend)\n",
    "            if ulist.has_key(str_friend):  #如果朋友也在训练集或测试集中出现\n",
    "                j = ulist[str_friend]   #朋友的索引\n",
    "\n",
    "            \n",
    "                #userEventScores为用户对活动的打分（interested - not interseted）\n",
    "                #在Users-Events.ipynb中计算好了\n",
    "                eventsForUser = userEventScores.getrow(j).todense()\n",
    "            \n",
    "                #所有朋友参加活动的数量（平均频率）\n",
    "                score = eventsForUser.sum() / np.shape(eventsForUser)[1]\n",
    "                userFriends[i, j] += score\n",
    "                userFriends[j, i] += score\n",
    "            \n",
    "fin.close()\n",
    "    \n",
    "\n",
    "#用户的朋友数目\n",
    "# 归一化数组\n",
    "sumNumFriends = numFriends.sum(axis=0)\n",
    "numFriends = numFriends / sumNumFriends\n",
    "sio.mmwrite(\"UF_numFriends\", np.matrix(numFriends))\n",
    "\n",
    "#\n",
    "userFriends = normalize(userFriends, norm=\"l2\", copy=False)\n",
    "sio.mmwrite(\"UF_userFriends\", userFriends)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
